package cz.tomasdvorak.cars.wicket.components.input;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;

/**
 * {@link Label} for use in a form: it has a {@code for} attribute pointing to specified (presumably
 * {@code input}) component. Tag in markup must be {@code label}.
 */
public class LabelForInput extends Label {
    public LabelForInput(String id, Component targetComponent) {
        super(id);
        addForAttrib(targetComponent);
    }

    public LabelForInput(String id, String label, Component targetComponent) {
        super(id, label);
        addForAttrib(targetComponent);
    }

    public LabelForInput(String id, IModel<?> model, Component targetComponent) {
        super(id, model);
        addForAttrib(targetComponent);
    }

    private void addForAttrib(final Component targetComponent) {
        targetComponent.setOutputMarkupId(true);
        // attribute "for" contains markupId of the target component
        this.add(new AttributeModifier("for", true, new AbstractReadOnlyModel<String>() {
            public String getObject() {
                return targetComponent.getMarkupId();
            }
        }));
    }

    @Override
    protected void onComponentTag(ComponentTag tag) {
        checkComponentTag(tag, "label");
        super.onComponentTag(tag);
    }
}
